﻿// <copyright file="CategoriesTasks.cs" company="Auros Ltd.">
//     Copyright (c) Auros Ltd. All rights reserved.
// </copyright>

namespace Auros.Categorisation.Umbraco
{
    using Auros.Categorisation.Data;

    /// <summary>
    /// Class representing the categories context menu main tasks.
    /// </summary>
    public class CategoriesTasks : umbraco.interfaces.ITaskReturnUrl
    {
        private string returnUrl;
        private int userId;

        #region Properties

        /// <summary>
        /// Gets the return URL.
        /// </summary>
        /// <value>The return URL.</value>
        public string ReturnUrl
        {
            get { return this.returnUrl; }
        }

        /// <summary>
        /// Gets or sets the alias.
        /// </summary>
        /// <value>The alias.</value>
        public string Alias
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the type ID.
        /// </summary>
        /// <value>The type ID.</value>
        public int TypeID
        {
            get;
            set;
        }

        /// <summary>
        /// Sets the user id.
        /// </summary>
        /// <value>The user id.</value>
        public int UserId
        {
            set { this.userId = value; }
        }

        /// <summary>
        /// Gets or sets the parent category ID.
        /// </summary>
        /// <value>The parent category ID.</value>
        public int ParentID
        {
            get;
            set;
        }

        #endregion

        /// <summary>
        /// Deletes the current node (ParentID).
        /// </summary>
        /// <returns>Returns true if the delete was successful.</returns>
        public bool Delete()
        {
            new CategoryRepository().Delete(this.ParentID);

            return true;
        }

        /// <summary>
        /// Saves the node under the selected node (ParentID).
        /// </summary>
        /// <returns>Returns true if the save was successful.</returns>
        public bool Save()
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            
            int parentId = this.ParentID < 0 ? 0 : this.ParentID;

            Category cat = null;

            if (parentId > 0)
                cat = categoryRepo.GetCategory(parentId);

            var category = categoryRepo.Add(
                new Category 
                {
                    Name = this.Alias,
                    Selectable = true,
                    ParentID = parentId,
                    Enabled = true
                });

            this.returnUrl = "plugins/Categorisation/EditCategory.aspx?id=" + category.ID;

            return true;
        }
    }
}